package com.my.utils;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @author mayong
 * @since 2024/7/23
 */
@Slf4j
@UtilityClass
public class HttpUtil {


    public static <T> T get(RestTemplate restTemplate, String url, HttpHeaders headers, Class<T> clazz) {
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<>(headers);
        ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET, request, clazz);
        if (response.getStatusCode().value() != 200) {
            log.error("请求发生异常, 返回码: " + response.getStatusCode().value());
        }
        return response.getBody();
    }

    public static <T> T postBody(RestTemplate restTemplate, String url, HttpHeaders headers, String json, Class<T> clazz) {
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<>(json, headers);
        ResponseEntity<T> response = restTemplate.postForEntity(url, request, clazz);
        if (response.getStatusCode().value() != 200) {
            log.error("请求发生异常, 返回码: " + response.getStatusCode().value());
        }
        return response.getBody();

    }

    public static <T> T put(RestTemplate restTemplate, String url, HttpHeaders headers, Class<T> clazz) {
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<>(headers);
        ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.PUT, request, clazz);
        if(response.getStatusCode().value() != 200){
            log.error("请求发生异常, 返回码: " + response.getStatusCode().value());
        }
        return response.getBody();
    }


    public static <T> T postByFormUrlencoded(RestTemplate restTemplate, String url, MultiValueMap<String, String> params, HttpHeaders headers, Class<T> clazz) {
        // 设置请求头
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
        return restTemplate.postForObject(url, request, clazz);
    }


}
